package com.gmu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gmu.domain.ResResult;
import com.gmu.pojo.TblSample;
import com.gmu.pojo.TblStudent;
import com.gmu.pojo.TblTeacher;
import com.gmu.pojo.TblUser;
import com.gmu.mapper.TblUserMapper;
import com.gmu.pojo.vo.RegisterVo;
import com.gmu.service.TblStudentService;
import com.gmu.service.TblTeacherService;
import com.gmu.service.TblUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 用户信息 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-07-24
 */
@Service
public class TblUserServiceImpl extends ServiceImpl<TblUserMapper, TblUser> implements TblUserService {

    public static final String username = "18679720725";
    public static final String password = "18679720725";
    public static final String token = "8ff6f7ef";
    public static final String templateid = "16C2835B";

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @Resource
    private TblUserService userService;
    
    @Resource
    private TblStudentService studentService;

    @Resource
    private TblTeacherService teacherService;

    @Autowired
    private  TblUserMapper tblUserMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    //修改用户信息
    @Override
    public ResResult updateUser(RegisterVo registerVo) {
        //获取修改信息，进行校验
        int userId = registerVo.getUserId();
        String telephone = registerVo.getTelephone();
        int roleId = registerVo.getRoleId();
        String code = registerVo.getCode();
        String school = registerVo.getSchool();
        String academy = registerVo.getAcademy();
        String className = registerVo.getClassName();
        String studentNumber = registerVo.getStudentNumber();
        String department = registerVo.getDepartment();
        String teacherNumber = registerVo.getTeacherNumber();
        String major = registerVo.getMajor();
        String grade = registerVo.getGrade();

        if(StringUtils.isEmpty(telephone) ||
                StringUtils.isEmpty(roleId) ||
                StringUtils.isEmpty(code) ||
                StringUtils.isEmpty(school) ||
                StringUtils.isEmpty(academy) ||
                StringUtils.isEmpty(major) ||
                (( StringUtils.isEmpty(className) ||
                        StringUtils.isEmpty(studentNumber) ||
                        StringUtils.isEmpty(grade)) &&
                        ( StringUtils.isEmpty(department) ||
                                StringUtils.isEmpty(teacherNumber))))
        {
//            throw new Exception("信息未填写完整，注册失败");
            return new ResResult<>(500,"信息未填写完整，修改失败");
        }

        //校验验证码
        String mobileCode = redisTemplate.opsForValue().get(telephone);
        if(!code.equals(mobileCode)){
            return new ResResult<>(500,"验证码不正确");
//            throw new Exception("验证码不正确");
        }

        //查询数据库中是否存在相同的手机号码
        Integer countMobile = baseMapper.selectCount(new
                QueryWrapper<TblUser>().ne("user_id",userId).eq("telephone", telephone));
        if(countMobile > 0) {
//            throw new Exception("该账号已被注册");
            return new ResResult<>(500,"该手机号码已被注册");
        }

        TblUser user = new TblUser();
        //将registerVo的值copy到user
        BeanUtils.copyProperties(registerVo,user);
        String password = registerVo.getPassword();
        if(!StringUtils.isEmpty(password)){
            user.setPassword(passwordEncoder.encode(password));
        }
        userService.updateById(user);
        //roleid==1，代表是学生
        if(roleId==1){
            TblStudent student = new TblStudent();
            BeanUtils.copyProperties(registerVo,student);
            QueryWrapper<TblStudent> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",userId);
            studentService.update(student,wrapper);
        }else if(roleId==2){
            TblTeacher tblTeacher = new TblTeacher();
            BeanUtils.copyProperties(registerVo,tblTeacher);
            QueryWrapper<TblTeacher> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",userId);
            teacherService.update(tblTeacher,wrapper);
        }
        return new ResResult(200,"修改成功");
    }

    //Pc端添加用户信息
    @SneakyThrows
    @Override
    public ResResult<?> add(RegisterVo registerVo) {

        //获取注册信息，进行校验
        String idNumber = registerVo.getIdNumber();
        String name = registerVo.getName();
        int volunteer = registerVo.getVolunteer();
        String telephone = registerVo.getTelephone();
        String password = registerVo.getPassword();
        String grade = registerVo.getGrade();
        String major = registerVo.getMajor();
        String address = registerVo.getAddress();
        int roleId = registerVo.getRoleId();
        String school = registerVo.getSchool();
        String academy = registerVo.getAcademy();
        String className = registerVo.getClassName();
        String studentNumber = registerVo.getStudentNumber();
        String department = registerVo.getDepartment();
        String teacherNumber = registerVo.getTeacherNumber();

        //校验参数
        if(StringUtils.isEmpty(idNumber) ||
                StringUtils.isEmpty(name) ||
                StringUtils.isEmpty(telephone) ||
                StringUtils.isEmpty(volunteer)||
                StringUtils.isEmpty(roleId) ||
                StringUtils.isEmpty(school) ||
                StringUtils.isEmpty(academy) ||
                StringUtils.isEmpty(major) ||
                (( StringUtils.isEmpty(className) ||
                        StringUtils.isEmpty(grade) ||
                        StringUtils.isEmpty(studentNumber)) &&
                        ( StringUtils.isEmpty(department) ||
                                StringUtils.isEmpty(teacherNumber))))
        {
//            throw new Exception("信息未填写完整，注册失败");
            return new ResResult<>(500,"信息未填写完整，添加失败");
        }

        //查询数据库中是否存在相同的身份证号码
        Integer count = baseMapper.selectCount(new
                QueryWrapper<TblUser>().eq("id_number", idNumber));
        if(count > 0) {
//            throw new Exception("该账号已被注册");
            return new ResResult<>(500,"该身份证已被注册");
        }

        //查询数据库中是否存在相同的手机号码
        Integer countMobile = baseMapper.selectCount(new
                QueryWrapper<TblUser>().eq("telephone", telephone));
        if(countMobile > 0) {
//            throw new Exception("该账号已被注册");
            return new ResResult<>(500,"该手机号码已被注册");
        }

        //查询数据库中是否存在相同的学号
        if(roleId==1){
            int countStudentId = studentService.count(new QueryWrapper<TblStudent>().eq("student_number", studentNumber));
            if(countStudentId > 0) {
//            throw new Exception("该账号已被注册");
                return new ResResult<>(500,"该学号已被注册");
            }
        }else if(roleId==2){
            int countTeacherId = teacherService.count(new QueryWrapper<TblTeacher>().eq("teacher_number", teacherNumber));
            if(countTeacherId > 0) {
//            throw new Exception("该账号已被注册");
                return new ResResult<>(500,"该老师工号已被注册");
            }
        }

        //数据添加到数据库
        TblUser tblUser = new TblUser();
        tblUser.setName(name);
        tblUser.setIdNumber(idNumber);
        tblUser.setTelephone(telephone);
        tblUser.setPassword(passwordEncoder.encode("123456"));
        tblUser.setRoleId(roleId);
        tblUser.setDelFlag(0);
//        BeanUtils.copyProperties(registerVo,tblUser);
        baseMapper.insert(tblUser);
        //根据身份证查询user_id，添加到学生表
        Integer userId = baseMapper.selectOne(new QueryWrapper<TblUser>().eq("id_number", idNumber)).getUserId();
        if(roleId==1){
            TblStudent tblStudent = new TblStudent();
//        tblStudent.setStudentNumber(studentNumber);
//        tblStudent.setTelephone(telephone);
//        tblStudent.setName(name);
//        tblStudent.setIdNumber(idNumber);
//        tblStudent.setSchool(school);
//        tblStudent.setAcademy(academy);
//        tblStudent.setClassName(className);
            BeanUtils.copyProperties(registerVo,tblStudent);
            tblStudent.setUserId(userId);
            studentService.save(tblStudent);
        }else if(roleId==2){
            TblTeacher tblTeacher = new TblTeacher();
            BeanUtils.copyProperties(registerVo,tblTeacher);
            tblTeacher.setUserId(userId);
            teacherService.save(tblTeacher);
        }
        return new ResResult<>(200,"添加成功");
    }

    //Pc端修改用户信息
    @Override
    public ResResult PcupdateUser(RegisterVo registerVo) {
        //获取修改信息，进行校验
        int userId = registerVo.getUserId();
        int volunteer = registerVo.getVolunteer();
        String telephone = registerVo.getTelephone();
        int roleId = registerVo.getRoleId();
        String school = registerVo.getSchool();
        String academy = registerVo.getAcademy();
        String className = registerVo.getClassName();
        String studentNumber = registerVo.getStudentNumber();
        String department = registerVo.getDepartment();
        String teacherNumber = registerVo.getTeacherNumber();
        String major = registerVo.getMajor();
        String grade = registerVo.getGrade();

        //校验参数
        if(StringUtils.isEmpty(telephone) ||
                StringUtils.isEmpty(roleId) ||
                StringUtils.isEmpty(volunteer)||
                StringUtils.isEmpty(school) ||
                StringUtils.isEmpty(academy) ||
                StringUtils.isEmpty(major) ||
                (( StringUtils.isEmpty(className) ||
                        StringUtils.isEmpty(grade) ||
                        StringUtils.isEmpty(studentNumber)) &&
                        ( StringUtils.isEmpty(department) ||
                                StringUtils.isEmpty(teacherNumber)))
        ){
//            throw new Exception("信息未填写完整，注册失败");
            return new ResResult<>(500,"信息未填写完整，修改失败");
        }

        //查询数据库中是否存在相同的手机号码
        Integer countMobile = baseMapper.selectCount(new
                QueryWrapper<TblUser>().ne("user_id",userId).eq("telephone", telephone));
        if(countMobile > 0) {
//            throw new Exception("该账号已被注册");
            return new ResResult<>(500,"该手机号码已被注册");
        }

        TblUser user = new TblUser();
        //将registerVo的值copy到user
        BeanUtils.copyProperties(registerVo,user);
        userService.updateById(user);
        //roleid==1，代表是学生
        if(roleId==1){
            TblStudent student = new TblStudent();
            BeanUtils.copyProperties(registerVo,student);
            QueryWrapper<TblStudent> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",userId);
            studentService.update(student,wrapper);
        }else if(roleId==2){
            TblTeacher tblTeacher = new TblTeacher();
            BeanUtils.copyProperties(registerVo,tblTeacher);
            QueryWrapper<TblTeacher> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",userId);
            teacherService.update(tblTeacher,wrapper);
        }
        return new ResResult(200,"修改成功");
    }
}
